package cn.steel.controller;

import cn.steel.domain.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Calendar;

@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @GetMapping("/login")
    public String login(HttpServletRequest request, Model model) {
        String referer = request.getHeader("Referer");
        String url = request.getParameter("url");
        logger.info("向登录页面跳转");

        if (url != null && !url.isEmpty()) {
            model.addAttribute("url", url);
        } else if (referer != null && !referer.contains("/login")) {
            model.addAttribute("url", referer);
        } else {
            model.addAttribute("url", "");
        }

        if (request.getParameter("error") != null) {
            model.addAttribute("errorMessage", "用户名或密码错误");
        }
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        logger.info("用户登出");
        session.invalidate();
        return "redirect:/login?logout=true";
    }

    @GetMapping("/error")
    public String error(Model model, @RequestParam(required = false) String accessDenied) {
        if ("true".equals(accessDenied)) {
            model.addAttribute("errorMessage", "您没有权限访问该页面");
        } else {
            model.addAttribute("errorMessage", "发生错误，请稍后重试");
        }
        return "error";
    }
    @GetMapping("/guestLogin")
    public String guestLogin(HttpSession session) {
        session.setAttribute("userType","guest");
        session.setAttribute("userId",-1L);
        //构造一个临时的对象
        User guestUser = new User();
        guestUser.setUsername("游客");
        guestUser.setRole("GUEST");
        session.setAttribute("user", guestUser);
        return "redirect:/";
    }
}